import { ItemView, WorkspaceLeaf, MarkdownView } from 'obsidian';

export const CODE_OUTLINE_VIEW = 'code-outline-view';

export class CodeOutlineView extends ItemView {
    constructor(leaf: WorkspaceLeaf) {
        super(leaf);
    }

    getViewType(): string {
        return CODE_OUTLINE_VIEW;
    }

    getDisplayText(): string {
        return '代码大纲';
    }

    async onOpen() {
        const container = this.containerEl.children[1];
        container.empty();
        container.createEl('div', { text: '代码大纲视图' });
        
        // 创建大纲容器
        const outlineContainer = container.createEl('div', {
            cls: 'code-outline-container'
        });

        // 监听当前文档变化
        this.registerEvent(
            this.app.workspace.on('active-leaf-change', () => {
                this.updateOutline(outlineContainer);
            })
        );

        // 初始更新
        this.updateOutline(outlineContainer);
    }

    private async updateOutline(container: HTMLElement) {
        const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
        if (!activeView) {
            container.empty();
            container.createEl('div', { text: '请打开一个 Markdown 文件' });
            return;
        }

        const content = activeView.getViewData();
        const outline = this.parseContent(content);
        this.renderOutline(container, outline);
    }

    private parseContent(content: string) {
        // 将内容解析为树形结构
        const lines = content.split('\n');
        const outline: OutlineNode[] = [];
        let currentNode: OutlineNode | null = null;
        let codeBlock = false;
        let codeContent = '';

        for (const line of lines) {
            if (line.startsWith('```')) {
                if (!codeBlock) {
                    codeBlock = true;
                    codeContent = '';
                } else {
                    if (currentNode) {
                        currentNode.codeBlocks.push(codeContent);
                    }
                    codeBlock = false;
                }
                continue;
            }

            if (codeBlock) {
                codeContent += line + '\n';
                continue;
            }

            // 处理标题层级
            const headingMatch = line.match(/^(#{1,6})\s+(.+)$/);
            if (headingMatch) {
                const level = headingMatch[1].length;
                const text = headingMatch[2];
                
                const newNode: OutlineNode = {
                    text,
                    level,
                    children: [],
                    codeBlocks: []
                };

                if (!currentNode || level <= currentNode.level) {
                    outline.push(newNode);
                } else {
                    currentNode.children.push(newNode);
                }
                currentNode = newNode;
            }
        }

        return outline;
    }

    private renderOutline(container: HTMLElement, outline: OutlineNode[]) {
        container.empty();
        const ul = container.createEl('ul', { cls: 'code-outline-list' });
        
        for (const node of outline) {
            this.renderNode(ul, node);
        }
    }

    private renderNode(parent: HTMLElement, node: OutlineNode) {
        const li = parent.createEl('li');
        li.createEl('span', { text: node.text });

        // 渲染代码块
        for (const code of node.codeBlocks) {
            const pre = li.createEl('pre');
            const codeEl = pre.createEl('code');
            codeEl.setText(code);
        }

        if (node.children.length > 0) {
            const childUl = li.createEl('ul');
            for (const child of node.children) {
                this.renderNode(childUl, child);
            }
        }
    }
}

interface OutlineNode {
    text: string;
    level: number;
    children: OutlineNode[];
    codeBlocks: string[];
} 